package student.aistar.watchorder;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;
import student.aistar.model.entity.Orders;
import student.aistar.service.IOrderService;
import student.aistar.service.IWatchSeckillService;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Component

public class WatchOrder {

    @Autowired
    private IWatchSeckillService watchSeckillService;

    @RabbitListener(queues = "xiaomi_wseckill")
    @RabbitHandler
    public void getWatchOrder(Map<String,Integer> map,@Headers Map<String,Object> header, Channel channel){
        Integer userId = map.get("userId");
        Integer killId = map.get("killId");

        //设置一个订单对象, 插入到订单表, 因为秒杀只有一个商品, 所以插入的数据大部分都是死的
        String orderNumber = new Date().getTime() + "" + userId;
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setOrderNumber(Long.valueOf(orderNumber));
        watchSeckillService.insertOrders(orders);
        watchSeckillService.insertOrderDetail(orders.getOrderId());

        //手动删除rabbitmq队列中的数据的.
        long ack = (long) header.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(ack,false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
